# coding: utf8
'''
用户注册
@author zhuxuezheng@gmail.com
'''
__revision__ = '0.1'

import hashlib
import web
from forms import registe_form
from models import User
from sqlalchemy.exc import IntegrityError
from SakyaTemplate import lookup

class Registe:
    def GET(self):
        form = registe_form()
        return lookup.get_template('user/registe.htm').render(form = form)

class DoRegiste:
    ''' 注册 '''
    def POST(self):
        form = registe_form()
        if not form.validates():
            return lookup.get_template('user/registe.htm').render(form = form)
        u_v = form.username.value
        # 32位加密密码
        p_hv = hashlib.md5(form.password.value).hexdigest()
        new_user = User(u_v, p_hv)
        e_user = web.ctx.orm.query(User).filter_by(username = u_v).first()
        if e_user:
            return '用户已经存在'

        try :
            web.ctx.orm.add(new_user)
            web.ctx.orm.flush()
        except IntegrityError, e:
            return lookup.get_template('user/registe.htm').render(form = form)
        raise web.seeother('login.htm')
        # 外部重定向(Y)
        #raise web.seeother("login.htm")
        #内部重定向
        #render.login()
        #可以的raise web.seeother("../test")
        #raise web.seeother("/") /user/
        #web.redirect("/123")
        #return render_index.test()

